package com.hsteach.service.wage;

import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.hsteach.common.config.App;
import com.hsteach.common.config.AppConfig;
import com.hsteach.common.core.domain.AjaxResult;
import com.hsteach.common.core.redis.RedisCache;
import com.hsteach.common.exception.ServiceException;
import com.hsteach.common.utils.DateUtils;
import com.hsteach.common.utils.SecurityUtils;
import com.hsteach.common.utils.StringUtils;
import com.hsteach.dao.domain.wage.*;
import com.hsteach.dao.mapper.wage.*;
import com.hsteach.enums.BooleanEnum;
import com.hsteach.enums.MsgTypeEnum;
import com.hsteach.enums.WageItemTypeEnum;
import com.hsteach.enums.WageNodeEnum;
import com.hsteach.framework.feign.client.xgk.dto.ret.GetTeacherRet;
import com.hsteach.service.third.MessageService;
import com.hsteach.service.third.XgkService;
import com.hsteach.util.WageTemplateUtil;
import com.hsteach.web.controller.wage.dto.AddBaseInfoDto;
import com.hsteach.web.controller.wage.dto.HandleRepeatDto;
import com.hsteach.web.controller.wage.dto.UpdateBaseInfoDto;
import com.hsteach.web.controller.wage.vo.*;
import com.hsteach.web.dto.PageDto;
import jodd.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 工资发布Service业务层处理
 *
 * @author fanxquer
 * @date 2023-07-16
 */
@Service
public class WageReleaseService {
    @Autowired
    private WageReleaseMapper wageReleaseMapper;

    @Autowired
    private WageTemplateItemsMapper wageTemplateItemsMapper;

    @Autowired
    private WageTempSnapshotMapper wageTempSnapshotMapper;

    @Autowired
    private WageDataMapper wageDataMapper;

    @Autowired
    private WageUserMapper wageUserMapper;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private XgkService xgkService;

    @Autowired
    private MessageService messageService;

    @Autowired
    private AppConfig appConfig;

    /**
     * 查询工资发布
     *
     * @param id 工资发布主键
     * @return 工资发布
     */
    public WageRelease selectWageReleaseById(Long id) {
        return wageReleaseMapper.selectWageReleaseById(id);
    }


    @Transactional(rollbackFor = Exception.class)
    public int commitRelease(Long id) {
        WageRelease wageRelease = wageReleaseMapper.selectWageReleaseById(id);
        wageRelease.setCurNode(WageNodeEnum.CHECK_INFO.getCode());
        wageRelease.setHasRelease(BooleanEnum.TRUE.getCode());
        wageRelease.setReleaseDate(new Date());
        if (BooleanEnum.TRUE.getCode().equals(wageRelease.getIsRecall())) {
            wageRelease.setIsRecall(BooleanEnum.FALSE.getCode());
            // 站内信
            WageUser userQuery = new WageUser();
            List<WageUser> wageUsers = wageUserMapper.selectWageUserList(userQuery);
            List<String> personIds = wageUsers.stream().map(WageUser::getUserId).collect(Collectors.toList());
            try {
                sendMsg(personIds, id, wageRelease.getReleaseName());
            } catch (Exception e) {
                e.printStackTrace();
            }
            return wageReleaseMapper.updateWageRelease(wageRelease);
        }
        Map<Integer, List<WageData>> importDatas = redisCache.getCacheObject("wage:import:" + id);

        wageRelease.setSendNum((long) importDatas.size());

        // 查询模板快照
        WageTempSnapshot query = new WageTempSnapshot();
        query.setReleaseId(id);
        List<WageTempSnapshot> items = wageTempSnapshotMapper.selectWageTempSnapshotList(query);
        // itemCode:itemType
        Map<String, Integer> collect = items.stream().collect(Collectors.toMap(WageTempSnapshot::getItemCode, WageTempSnapshot::getItemType));
        // 统计每条数据应发，扣款
        List<WageUser> wageUsers = importDatas.values().stream().map(e -> {
            WageUser wageUser = new WageUser();
            wageUser.setReleaseId(id);
            wageUser.setUserId(e.get(0).getUserId());
            // 统计应发
            List<String> accrued = e.stream().filter(k -> WageItemTypeEnum.ACCRUED.getCode().equals(collect.get(k.getItemCode())))
                    .map(WageData::getItemValue).collect(Collectors.toList());
            wageUser.setSumAccruedAmt(sum(accrued));
            // 统计扣款
            List<String> deduction = e.stream().filter(k -> WageItemTypeEnum.DEDUCTION.getCode().equals(collect.get(k.getItemCode())))
                    .map(WageData::getItemValue).collect(Collectors.toList());
            wageUser.setSumDeductionAmt(sum(deduction));
            // 实发=应发-扣款
            wageUser.setSumAmt(wageUser.getSumAccruedAmt().subtract(wageUser.getSumDeductionAmt()));
            return wageUser;
        }).collect(Collectors.toList());
        wageUserMapper.batchInsert(wageUsers);

        // 站内信
        List<String> personIds = wageUsers.stream().map(WageUser::getUserId).collect(Collectors.toList());
        try {
            sendMsg(personIds, id, wageRelease.getReleaseName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 发布完成后将redis缓存数据删除
        redisCache.deleteObject("wage:import:" + id);
        return wageReleaseMapper.updateWageRelease(wageRelease);
    }

    private boolean sendMsg(List<String> personIds, Long id, String name) {
        App app = appConfig.getConfig().get(SecurityUtils.getAuthInfo().getAppId());
        if (app == null) {
            return false;
        }
        String msg = "请查收" + name + "工资条";
        String params = "&msgId=" + id;
        String url = app.getRedirectUrl() + params;
        String content = "<p>" + msg + "<a href=\"" + url + "\">跳转进应用</a></p>";
        List<GetTeacherRet> teachers = xgkService.getTeachers(SecurityUtils.getAuthInfo().getId());
        List<String> ids = teachers.stream().filter(
                e -> personIds.contains(e.getPersonId())
                && StringUtil.isNotEmpty(e.getT_userID()))
                .map(GetTeacherRet::getT_userID).collect(Collectors.toList());
        return messageService.sendMsg(content, ids, MsgTypeEnum.WAGE_NOTIFY, msg);
    }

    public BigDecimal sum(List<String> amts) {
        return amts.stream().map(e -> new BigDecimal(e)).reduce(BigDecimal.ZERO, BigDecimal::add);
    }

    /**
     * 查询工资发布列表
     *
     * @param wageRelease 工资发布
     * @return 工资发布
     */
    public List<WageRelease> selectWageReleaseList(WageRelease wageRelease) {
        return wageReleaseMapper.selectWageReleaseList(wageRelease);
    }

    /**
     * 查询工资条列表
     *
     * @return
     */
    public List<AppWageListVo> selectWageList(PageDto dto) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<AppWageListVo> appWageListVos = wageUserMapper.selectWageList(SecurityUtils.getAuthInfo().getPersonId(), null);
        return appWageListVos;
    }

    /**
     * 查询工资条详情
     *
     * @param id
     * @return
     */
    public Map<String, Object> selectWageInfo(Long id) {
        WageRelease release = wageReleaseMapper.selectWageReleaseById(id);
        if (release == null) {
            throw new ServiceException("数据不存在");
        }
        if (BooleanEnum.TRUE.getCode().equals(release.getIsRecall())) {
            throw new ServiceException("工资条已被管理员撤回");
        }
        if (BooleanEnum.TRUE.getCode().equals(release.getDelFlg())) {
            throw new ServiceException("工资条已被管理员删除");
        }
        // 表格数据明细
        WageData query = new WageData();
        query.setReleaseId(id);
        query.setUserId(SecurityUtils.getAuthInfo().getPersonId());
        List<WageData> datas = wageDataMapper.selectWageDataList(query);

        // 模板快照
        WageTempSnapshot query2 = new WageTempSnapshot();
        query2.setReleaseId(id);
        List<WageTempSnapshot> items = wageTempSnapshotMapper.selectWageTempSnapshotList(query2);
        Map<String, WageTempSnapshot> collect = items.stream().collect(Collectors.toMap(WageTempSnapshot::getItemCode, Function.identity()));
        Map<Integer, List<WageData>> groupByType = datas.stream().collect(Collectors.groupingBy(e -> collect.get(e.getItemCode()).getItemType()));

        // 按数据类型分组返回
        List<Map<String, Object>> ret = groupByType.entrySet().stream().map(e -> {
            Map<String, Object> types = Maps.newHashMap();
            types.put("type", e.getKey());
            List<Map<String, String>> kvs = e.getValue().stream()
                    .filter(k ->!"姓名".equals(collect.get(k.getItemCode()).getItemName()))
                    .filter(k ->!"身份证号".equals(collect.get(k.getItemCode()).getItemName())).map(k -> {
                Map<String, String> kv = Maps.newHashMap();
                kv.put("itemName", collect.get(k.getItemCode()).getItemName());
                kv.put("itemValue", k.getItemValue());
                return kv;
            }).collect(Collectors.toList());
            types.put("items", kvs);
            return types;
        }).collect(Collectors.toList());

        Map<String, Object> data = Maps.newHashMap();
        List<AppWageListVo> appWageListVos = wageUserMapper.selectWageList(SecurityUtils.getAuthInfo().getPersonId(), id);
        if (appWageListVos.size() > 0) {
            data.put("wage", appWageListVos.get(0));
        }

        // 调整其他栏排序
        if (ret.size() > 0) {
            Map<String, Object> stringObjectMap = ret.get(0);
            if ((Integer) stringObjectMap.get("type") == 1) {
                Map<String, Object> remove = ret.remove(0);
                ret.add(remove);
            }
        }
        data.put("values", ret);

        return data;
    }

    /**
     * 导入表格文件并校验
     *
     * @param id
     * @param is
     * @return
     * @throws Exception
     */
    public AjaxResult importFile(Long id, InputStream is) throws Exception {
        WageTemplateUtil<WageTemplate> util = new WageTemplateUtil<WageTemplate>(WageTemplate.class);
        WageTempSnapshot query = new WageTempSnapshot();
        query.setReleaseId(id);
        List<WageTempSnapshot> items = wageTempSnapshotMapper.selectWageTempSnapshotList(query);
        // 载入模板字段
        util.setItems(items);
        // 从表格读取数据
        List<Map<Integer, String>> maps = util.importExcel("", is, 0);
        if (maps.size() == 0) {
            throw new ServiceException("数据为空，请填写数据再上传");
        }
        Map<String, Integer> cellMap = util.getCellMap();
        // 校验表格字段与模板字段顺序是否一致，以及是否缺少列
        boolean ret = true;
        for (int i = 0; i < items.size(); i++) {
            WageTempSnapshot item = items.get(i);
            String itemName = item.getItemName();
            Integer index = cellMap.get(itemName);
            if (index == null || !index.equals(i)) {
                ret = false;
                break;
            }
        }
        if (!ret || items.size() != cellMap.size()) {
            throw new ServiceException("模板不一致，请重新下载");
        }
        // 获取姓名,身份证列位置
        Integer nameIndex = cellMap.get("姓名");
        Integer idCardIndex = cellMap.get("身份证号");
        //导入的教职工身份证号与姓名
        Map<String, String> importTeacher = new HashMap<>();
        maps.forEach(e -> {
            if (!StringUtils.isNotEmpty(e.get(nameIndex))  ||  !StringUtils.isNotEmpty(e.get(idCardIndex))) {
                throw new ServiceException("表格数据不完整，请检查");
            }
            if (importTeacher.containsKey(e.get(idCardIndex))){
                throw new ServiceException("表格数据有重复，请检查:"+e.get(idCardIndex)+","+e.get(nameIndex));
            }
            importTeacher.put(e.get(idCardIndex), e.get(nameIndex));
        });

        //查询平台所有教职工
        List<GetTeacherRet> teachers = xgkService.getTeachers(SecurityUtils.getAuthInfo().getId());
        // 平台教职工身份证号与姓名
        Map<String, String> teacherInfo = teachers.stream()
                .filter(e -> e.getIdcardNo() != null && e.getName() != null)
                .collect(Collectors.toMap(GetTeacherRet::getIdcardNo, GetTeacherRet::getName));

        //存放与平台数据匹配不上的数据
        Map<String, String> differenceMap = new HashMap<>();
//        导入数据和平台数据匹配
        for (Map.Entry<String, String> entry : importTeacher.entrySet()) {
            if (!teacherInfo.containsKey(entry.getKey()) ||
                    !teacherInfo.get(entry.getKey()).equals(entry.getValue())) {
                differenceMap.put(entry.getKey(), entry.getValue());
            }
        }

        if (differenceMap.size() > 0) {
//             使用StringBuilder构建字符串
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, String> entry : differenceMap.entrySet()) {
                sb.append(entry.getKey()).append(" , ").append(entry.getValue()).append("\n");
            }
            throw new ServiceException("以下身份核对基础数据不存在，请仔细核对:"+"\n"+sb);
//            AjaxResult repeat = AjaxResult.success("身份核对基础数据不存在，请仔细核对", differenceMap);
//            repeat.put("code", -2);
//            return repeat;
        }
        // 校验、处理数据结构
        List<GetTeacherRet> teacherRetList = teachers.stream()//通过这个获取userId
                .filter(e -> e.getIdcardNo() != null && e.getName() != null && e.getT_userID() != null).collect(Collectors.toList());
        Map<Integer, List<WageData>> importDatas = Maps.newHashMap();
        Set<String> tableNames = Sets.newHashSet();
        for (int i = 0; i < maps.size(); i++) {
            Map<Integer, String> e = maps.get(i);//List<Map<行号, 数据名称>>
            String idCardNo = e.get(idCardIndex);//身份证号
            List<WageData> datas = Lists.newArrayList();
            for (int j = 0; j < e.size(); j++) {
                List<GetTeacherRet> collect = teacherRetList.stream().filter(t -> t.getIdcardNo().equals(idCardNo)).collect(Collectors.toList());
                if (collect == null || collect.size() == 0){
                    throw new ServiceException("身份核对基础数据不存在，请仔细核对:"+idCardNo+","+e.get(idCardIndex));
                }
                GetTeacherRet teacherRet = collect.get(0);//获取教职工信息
                WageTempSnapshot item = items.get(j);
                String value = e.get(j);
                WageData data = new WageData();
                data.setUserId(teacherRet.getPersonId());//教职工PersonId
                data.setItemCode(item.getItemCode());
                data.setItemValue(value);
                data.setRowNum((long) i);
                data.setReleaseId(id);
                datas.add(data);
                if (WageItemTypeEnum.ACCRUED.getCode().equals(item.getItemType()) || WageItemTypeEnum.DEDUCTION.getCode().equals(item.getItemType())) {
                    if (StringUtils.isEmpty(value)) {
                        tableNames.add(item.getItemName());
                    } else if (!isSumPoint2(value)) {
                        tableNames.add(item.getItemName());
                    }
                }
            }
            importDatas.put(i, datas);
        }

        if (tableNames.size() > 0) {
            String join = String.join(",", tableNames);
            throw new ServiceException("以下数据项填写不规范，请填写两个小数点的数字:" + join);
        }

        // 将处理好的数据放至
        redisCache.setCacheObject("wage:import:" + id, importDatas, 1, TimeUnit.DAYS);
        return AjaxResult.success("校验通过",importDatas);
    }

    private boolean isSumPoint2(String s) {
        String pattern = "^[0-9]+\\.{0,1}[0-9]{0,2}$";
        return s.matches(pattern);
    }

    /**
     * 处理重名数据
     *
     * @param dto
     * @return
     */
    public boolean handleRepeat(HandleRepeatDto dto) {
        Map<Integer, List<WageData>> importDatas = redisCache.getCacheObject("wage:import:" + dto.getReleaseId());
        dto.getRepeatRets().stream().forEach(e -> {
            List<WageData> data = importDatas.get(e.getRowNum());
            data.stream().forEach(k -> k.setUserId(e.getUserId()));
            importDatas.put(e.getRowNum(), data);
        });
        redisCache.setCacheObject("wage:import:" + dto.getReleaseId(), importDatas, 1, TimeUnit.DAYS);
        return true;
    }

    /**
     * 查询表格数据
     *
     * @param id
     * @return
     */
    public WageDataVo getWageData(Long id) {
        WageTempSnapshot itemQuery = new WageTempSnapshot();
        itemQuery.setReleaseId(id);
        List<WageTempSnapshot> items = wageTempSnapshotMapper.selectWageTempSnapshotList(itemQuery);
        WageData dataQuery = new WageData();
        dataQuery.setReleaseId(id);
        List<WageData> datas = wageDataMapper.selectWageDataList(dataQuery);
        return buildWageData(items, datas);
    }

    /**
     * 将数据和模板组合成前端需要的格式
     *
     * @param items
     * @param datas
     * @return
     */
    public WageDataVo buildWageData(List<WageTempSnapshot> items, List<WageData> datas) {
        Map<Long, List<WageData>> groupByRow = datas.stream().collect(Collectors.groupingBy(WageData::getRowNum));
//        List<WageDataRow> retDatas = groupByRow.entrySet().stream().map(e -> {
//            Map<String, String> map = e.getValue().stream().collect(Collectors.toMap(WageData::getItemCode, WageData::getItemValue));
//            List<String> collect = items.stream().map(k -> map.get(k.getItemCode())).collect(Collectors.toList());
//            WageDataRow row = new WageDataRow();
//            row.setRow(e.getKey());
//            row.setValues(collect);
//            return row;
//        }).collect(Collectors.toList());
//        List<String> heads = items.stream().map(WageTempSnapshot::getItemName).collect(Collectors.toList());
        List<WageDataColumn> heads = items.stream().map(e -> {
            WageDataColumn column = new WageDataColumn();
            column.setKey(e.getItemCode());
            column.setTitle(e.getItemName());
            column.setDataIndex(e.getItemCode());
            return column;
        }).collect(Collectors.toList());
        List<Map<String, String>> retDatas = groupByRow.entrySet().stream().map(e -> {
            Map<String, String> row = Maps.newHashMap();
            e.getValue().stream().forEach(k -> {
                row.put(k.getItemCode(), k.getItemValue());
            });
            return row;
        }).collect(Collectors.toList());
        WageDataVo retVo = new WageDataVo();
        retVo.setDataSource(retDatas);
        retVo.setColumns(heads);
        return retVo;
    }

    /**
     * 上传表格确认
     *
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int importCompleted(Long id) {
        WageRelease wageRelease = wageReleaseMapper.selectWageReleaseById(id);
        wageRelease.setCurNode(WageNodeEnum.UPLOAD_FILE.getCode());
        Map<Integer, List<WageData>> importDatas = redisCache.getCacheObject("wage:import:" + id);
        List<WageData> datas = importDatas.values().stream().flatMap(Collection::stream).collect(Collectors.toList());
        datas = covertToNum(id, datas);
        wageDataMapper.deleteWageDataByReleaseId(id);
        wageDataMapper.batchInsert(datas);
        return wageReleaseMapper.updateWageRelease(wageRelease);
    }

    /**
     * 将应发类型和扣款类型字段转换成保留两位小数，尝试性将其他类型转换为保留两位小数
     *
     * @param id
     * @param datas
     * @return
     */
    private List<WageData> covertToNum(Long id, List<WageData> datas) {
        WageTempSnapshot query = new WageTempSnapshot();
        query.setReleaseId(id);
        List<WageTempSnapshot> items = wageTempSnapshotMapper.selectWageTempSnapshotList(query);
        Map<String, Integer> collect = items.stream().collect(Collectors.toMap(WageTempSnapshot::getItemCode, WageTempSnapshot::getItemType));
        datas = datas.stream().map(e -> {
            if (WageItemTypeEnum.ACCRUED.getCode().equals(collect.get(e.getItemCode())) || WageItemTypeEnum.DEDUCTION.getCode().equals(collect.get(e.getItemCode()))) {
                BigDecimal value = new BigDecimal(e.getItemValue());
                BigDecimal bigDecimal = value.setScale(2, BigDecimal.ROUND_HALF_UP);
                e.setItemValue(bigDecimal.toString());
            } else {
                if (!e.getItemCode().equals("sfzh")){
                    try {
                        BigDecimal value = new BigDecimal(e.getItemValue());
                        BigDecimal bigDecimal = value.setScale(2, BigDecimal.ROUND_HALF_UP);
                        e.setItemValue(bigDecimal.toString());
                    } catch (Exception err) {

                    }
                }
            }
            return e;
        }).collect(Collectors.toList());
        return datas;
    }

    /**
     * 新增工资发布
     *
     * @param wageRelease 工资发布
     * @return 结果
     */
    public int insertWageRelease(WageRelease wageRelease) {
        wageRelease.setCreateTime(DateUtils.getNowDate());
        return wageReleaseMapper.insertWageRelease(wageRelease);
    }

    /**
     * 填写基本信息
     *
     * @param dto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Long addBaseInfoDto(AddBaseInfoDto dto) {
        WageRelease queryV = new WageRelease();
        queryV.setDelFlg(BooleanEnum.FALSE.getCode());
        queryV.setReleaseName(dto.getReleaseName());
        List<WageRelease> wageReleases = wageReleaseMapper.selectWageReleaseList(queryV);
        if (wageReleases.size() > 0) {
            throw new ServiceException("工资发布名称已存在");
        }
        WageRelease wageRelease = new WageRelease();
        BeanUtils.copyProperties(dto, wageRelease);
        wageRelease.setCurNode(WageNodeEnum.UPLOAD_FILE.getCode());
        wageRelease.setHasRelease(BooleanEnum.FALSE.getCode());
        wageRelease.setIsRecall(BooleanEnum.FALSE.getCode());
        wageRelease.setDelFlg(BooleanEnum.FALSE.getCode());
        wageRelease.setOrgCode(SecurityUtils.getAuthInfo().getOrgCode());

        WageTemplateItems query = new WageTemplateItems();
        query.setTemplateId(dto.getTemplateId());
        query.setStatus(BooleanEnum.TRUE.getCode());
        List<WageTemplateItems> items = wageTemplateItemsMapper.selectWageTemplateItemsList(query);

        int i = wageReleaseMapper.insertWageRelease(wageRelease);
        // 保存模板快照
        List<WageTempSnapshot> snapshots = items.stream().map(e -> {
            WageTempSnapshot snapshot = new WageTempSnapshot();
            BeanUtils.copyProperties(e, snapshot);
            snapshot.setId(null);
            snapshot.setReleaseId(wageRelease.getId());
            return snapshot;
        }).collect(Collectors.toList());

        wageTempSnapshotMapper.batchInsert(snapshots);
        wageRelease.setCreateTime(DateUtils.getNowDate());
        return wageRelease.getId();
    }

    /**
     * 修改基本信息，返回true代表修养了模板，false代表没有
     *
     * @param dto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateBaseInfoDto(UpdateBaseInfoDto dto) {
        WageRelease release = wageReleaseMapper.selectWageReleaseById(dto.getId());
        if (release == null) {
            throw new ServiceException("无法修改，请重新创建");
        }
        WageRelease queryV = new WageRelease();
        queryV.setDelFlg(BooleanEnum.FALSE.getCode());
        queryV.setReleaseName(dto.getReleaseName());
        List<WageRelease> wageReleases = wageReleaseMapper.selectWageReleaseList(queryV);
        if (wageReleases.size() > 0) {
            throw new ServiceException("工资发布名称已存在");
        }
        WageRelease wageRelease = new WageRelease();
        BeanUtils.copyProperties(dto, wageRelease);
        // 修改模板，重新保存模板快照
        if (!dto.getTemplateId().equals(release.getTemplateId())) {
            wageRelease.setCurNode(WageNodeEnum.UPLOAD_FILE.getCode());
            wageRelease.setHasRelease(BooleanEnum.FALSE.getCode());
            wageRelease.setIsRecall(BooleanEnum.FALSE.getCode());
            wageRelease.setDelFlg(BooleanEnum.FALSE.getCode());
            wageRelease.setOrgCode(SecurityUtils.getAuthInfo().getOrgCode());
            // 删除原模板快照
            wageTempSnapshotMapper.deleteByReleaseId(release.getId());
            WageTemplateItems query = new WageTemplateItems();
            query.setTemplateId(dto.getTemplateId());
            query.setStatus(BooleanEnum.TRUE.getCode());
            List<WageTemplateItems> items = wageTemplateItemsMapper.selectWageTemplateItemsList(query);
            // 保存模板快照
            List<WageTempSnapshot> snapshots = items.stream().map(e -> {
                WageTempSnapshot snapshot = new WageTempSnapshot();
                BeanUtils.copyProperties(e, snapshot);
                snapshot.setId(null);
                snapshot.setReleaseId(dto.getId());
                return snapshot;
            }).collect(Collectors.toList());
            wageTempSnapshotMapper.batchInsert(snapshots);
            wageReleaseMapper.updateWageRelease(wageRelease);
            // 删除上传表格数据
            redisCache.deleteObject("wage:import:" + dto.getId());
            return true;
        }

        wageReleaseMapper.updateWageRelease(wageRelease);
        return false;
    }

    /**
     * 修改工资发布
     *
     * @param wageRelease 工资发布
     * @return 结果
     */
    public int updateWageRelease(WageRelease wageRelease) {
        wageRelease.setUpdateTime(DateUtils.getNowDate());
        return wageReleaseMapper.updateWageRelease(wageRelease);
    }

    /**
     * 批量删除工资发布
     *
     * @param ids 需要删除的工资发布主键
     * @return 结果
     */
    public int deleteWageReleaseByIds(Long[] ids) {
        return wageReleaseMapper.deleteWageReleaseByIds(ids);
    }

    /**
     * 删除工资发布信息
     *
     * @param id 工资发布主键
     * @return 结果
     */
    public int deleteWageReleaseById(Long id) {
        return wageReleaseMapper.updateDelById(id);
    }

    /**
     * 撤回
     *
     * @param id
     * @return
     */
    public int recallById(Long id) {
        return wageReleaseMapper.updateRecallById(id);
    }
}
